package com.wk.springboot.parse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class PayloadBuilder {
    protected static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 构建消息内容
     * @param payloadClass 目标类型
     * @param args 方法参数
     * @return JSON字符串
     */
    public String buildPayload(Class<?> payloadClass, Object[] args) throws Exception {
        if (payloadClass == Object.class) {
            return buildDefaultPayload(args);
        }
        
        Object payload = Arrays.stream(args)
                .filter(payloadClass::isInstance)
                .findFirst()
                .orElseThrow(() -> new Exception("未找到匹配的payload参数"));
        
        return serialize(payload);
    }

    /**
     * 默认参数处理（自动查找第一个可序列化参数）
     */
    private String buildDefaultPayload(Object[] args) throws Exception {
         String result = Arrays.stream(args)
                .filter(this::isSerializable)
                .findFirst()
                .map(this::serialize)
                .orElseThrow(() -> new Exception("未找到可序列化的参数"));
        return result;
    }

    private boolean isSerializable(Object obj) {
        try {
            objectMapper.writeValueAsString(obj);
            return true;
        } catch (JsonProcessingException e) {
            return false;
        }
    }

    private String serialize(Object obj)  {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
        }
        return "";
    }
}